import React, { useState, useEffect } from 'react'
import CommonTable from '@/common/CommonTable'
import { tableConfig, actions } from './config'
import _ from 'lodash'
import CommonFetch from '@/config/CommonFetch'
import ChildrenTable from './ChildrenTable'
import { TableChildrenTableContext } from '@/config/globalContext'

const TableChildrenTable = () => {
  const [data, setData] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [allButton, setAllButton] = useState(false)
  const { Provider } = TableChildrenTableContext
  useEffect(() => {
    CommonFetch.get('/hdk/tableChildrenTable').then((ret) => {
      if (ret.data) {
        const filterData = _.filter(ret.data, (o) => o.childrenTable)
        const newData = _.map(filterData, (item, key) => {
          return { ...item, childrenTable: <ChildrenTable /> }
        })
        setData(newData)
      }
    })
  }, [])
  const handlerClick = () => {
    setAllButton(!allButton)
    // 因为使用useState中的修改数据源是异步操作
    // 所以当allButton 为 true的时候,那么点击之后就是false
    // 所以当allButton为 true的时候,就是要清空selectedRowKeys
    // 反向走的!!1
    if (allButton) {
      setSelectedRowKeys([])
    } else {
      setSelectedRowKeys(_.map(data, (item, key) => item.id))
    }
  }
  const actionsClick = {
    all: () => handlerClick(),
  }
  const tableProps = {
    columns: tableConfig,
    dataSource: data,
    expandable: {
      // eslint-disable-next-line react/display-name
      expandedRowRender: (record, index, indent, expanded) => {
        console.log(record)
        return <div style={{ marginLeft: '80px' }}>{record.childrenTable}</div>
      },
    },
    rowKey: 'id',
    actions: _.map(actions, (item, key) => {
      const obj = { ...item }
      obj.onClick = actionsClick[item.id]
      return obj
    }),
    rowSelection: {
      selectedRowKeys,
      onChange: (val, row) => {
        setSelectedRowKeys(val)
      },
    },
  }
  return (
    <div>
      <Provider value={{ allButton }}>
        <CommonTable {...tableProps} />
      </Provider>
    </div>
  )
}

export default TableChildrenTable
